/**
 * Copyright (c) 2011-9-23 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.task.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wkm.util.Configuration;
import org.wkm.util.Home;

/**
 * The class note
 * @version 1.0 2011-12-13
 * @author WUKUNMENG
 */
public class TaskReader {

	private static Logger logger = LoggerFactory.getLogger(TaskReader.class);
	
	private Hashtable<String,File> table = new Hashtable<String,File>();
	
	private TaskReader(){
		try {
			read();
		} catch (IOException e) {
			// TODO: handle exception
			logger.info("读取配置文件失败:" + Configuration.TASK_CONFIG);
			e.printStackTrace();
		}
	}
	
	public static TaskReader getInstance() {
		return new TaskReader();
	}
	
	private void read() throws IOException {

		
		File file = new File(Home.getPath(Configuration.TASK_CONFIG));
		
		if(!file.exists()){
			logger.error("不能找到任务目录:" + file.getCanonicalPath());
			return ;
		}
		
		File[] files = file.listFiles();
		
		if(files == null || files.length == 0){
			logger.info(file.getCanonicalPath() + "目录下没有任务文件");
			return ;
		}
		
		for(File f : files){
			if(f.isDirectory()){
				f.delete();
				continue;
			}
			logger.info("装载任务文件:" + f.getName());
			table.put(f.getName(), f);
		}
	}
	
	
	public Properties getProperties(String name){
		
		if(table.get(name) == null){
			return null;
		}
		
		Properties res = new Properties();
		
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(table.get(name));
		
			if (inStream != null) {
				logger.info("读取文件成功:" + table.get(name).getName());
				res.load(inStream);
				inStream.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("不能找到文件:" + table.get(name).getName());
			logger.error(e.getMessage());
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("读取文件错误:" + table.get(name).getName());
			logger.error(e.getMessage());
			return null;
		}
		
		return res;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TaskReader.getInstance();
	}

}
